// 2013-9-4上午11:34:49  net.betou.web.IpAddressDirective.java

package net.betou.web;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import net.betou.common.ipseek.IPLocation;
import net.betou.common.ipseek.IPSeeker;
import net.betou.web.freemaker.DirectiveUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 
 * @author 叶装装
 */
public class IpAddressDirective implements TemplateDirectiveModel{

	public static final String IP = "ip";

	@SuppressWarnings( "unchecked" )
	public void execute( Environment env, Map params, TemplateModel [ ] loopVars, TemplateDirectiveBody body ) throws TemplateException, IOException {

		String ip = DirectiveUtils.getString( IP, params );

		String address;

		if( StringUtils.isBlank( ip ) ){
			address = ip;
		}else{
			IPLocation location = ipSeeker.getIPLocation( ip );
			address = location.getCountry( ) + " " + location.getArea( );
		}

		Writer out = env.getOut( );
		out.append( address );
	}

	@Autowired
	private IPSeeker ipSeeker;
}
